var mssql = require('mssql');

var SqlHelper = function () {
    var connPool;
    var helper = {};

    helper.setup = function (dbConfig) {
        connPool = new mssql.ConnectionPool(dbConfig, err => {
            if (err) {
                console.log(err);
            }
        });
    };

    //执行sql,返回数据.  
    helper.query = function (sql, callBack) {
        new mssql.Request(connPool).query(sql, (err, result) => {
            callBack(err, result);
        });
    };

    helper.request = function () {
        return new mssql.Request(connPool);
    };

    //执行存储过程,返回数据
    helper.exec = function (procName, params, callBack) {
        var sql = helper.request();

        if (params != "") {
            for (var index in params) {
                if (typeof params[index] == "number") {
                    sql.input(index, mssql.Int, params[index]);
                } else if (typeof params[index] == "string") {
                    sql.input(index, mssql.NVarChar, params[index]);
                }
            }
        }

        sql.execute(procName, (err, result) => {
            return callBack(err, result);
        });
    }

    return helper;
}();
module.exports = SqlHelper;